package com.amphiprion.prototype.component;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;

import com.amphiprion.prototype.ScreenProperty;
import com.amphiprion.prototype.util.BitmapUtil;
import com.amphiprion.prototype.util.NormalizedBitmap;

public class SpriteComponent extends GameComponent {
	private String imageUri;
	public NormalizedBitmap bitmap;
	protected Paint paint;
	protected int cols;
	protected int rows;
	private int frames;
	private int frameIndex = 0;
	private Bitmap currentBitmap;

	public SpriteComponent(String imageUri, float x, float y, int cols, int rows, int frames) {
		this(imageUri, x, y, cols, rows, frames, 255);
	}

	public SpriteComponent(String imageUri, float x, float y, int cols, int rows, int frames, int alpha) {
		this.imageUri = imageUri;
		this.x = x;
		this.y = y;
		this.cols = cols;
		this.rows = rows;
		this.alpha = alpha;
		this.frames = frames;
		paint = new Paint();
		// paint.setAntiAlias(true);
	}

	public int getFrameIndex() {
		return frameIndex;
	}

	public void setFrameIndex(int frameIndex) {
		this.frameIndex = frameIndex;
		buildCurrentBitmap();
	}

	public int getFrameCount() {
		return frames;
	}

	@Override
	public void activate() {
		bitmap = BitmapUtil.loadBitmap(imageUri);
		buildCurrentBitmap();
	}

	@Override
	public void desactivate() {
		BitmapUtil.unloadBitmap(imageUri);
	}

	@Override
	public void onDraw(Canvas canvas, ScreenProperty screenProperty) {
		drawImage(canvas, currentBitmap, x, y, scale, screenProperty);
	}

	private void buildCurrentBitmap() {
		int width = bitmap.bitmap.getWidth() / cols;
		int height = bitmap.bitmap.getHeight() / rows;
		currentBitmap = Bitmap.createBitmap(bitmap.bitmap, frameIndex % cols * width, frameIndex / cols * height, width, height);
	}

	protected void drawImage(Canvas canvas, Bitmap img, float centerX, float centerY, float scale, ScreenProperty screenProperty) {

		if (alpha == 0) {
			return;
		}
		paint.setAlpha(alpha);
		Matrix m = new Matrix();
		m.postTranslate(-img.getWidth() / 2, -img.getHeight() / 2);
		m.postRotate(screenProperty.screenRotation);
		m.postScale(bitmap.normalizedScale * scale * screenProperty.screenScale, bitmap.normalizedScale * scale * screenProperty.screenScale);

		if (screenProperty.screenRotation == 0) {
			m.postTranslate(centerX * screenProperty.screenScale + screenProperty.screenOffsetX, centerY * screenProperty.screenScale + screenProperty.screenOffsetY);
		} else {
			m.postTranslate(canvas.getWidth() - centerY * screenProperty.screenScale + screenProperty.screenOffsetX, centerX * screenProperty.screenScale
					+ screenProperty.screenOffsetY);
		}
		canvas.drawBitmap(img, m, paint);
	}
}
